//工具库
const formatDate = (timesTamp, type) => {
	var timesTamp = timesTamp ? timesTamp : new Date().getTime();
	var _date = new Date(timesTamp);
  var paddingStr = function (_str) {
    return _str.length == 1 ? "0" + _str : _str
  }	
	var week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  var _yyyy = _date.getFullYear();
	var _MM = _date.getMonth() + 1 + '';
	_MM = paddingStr(_MM);
	var _dd = _date.getDate() + "";
	_dd = paddingStr(_dd);
	var _hh = _date.getHours() + "";
	_hh = paddingStr(_hh);
  var _mm = _date.getMinutes() + "";
  _mm = paddingStr(_mm)	
	var _ss = _date.getSeconds() + "";
	_ss = paddingStr(_ss)	
	var _week = week[_date.getDay()]
	switch (type) {
		case '0':
			return `${_MM}-${_dd}`;
			break;
		case '1':
			return `${_week}`;
			break;
		case '2':
			return `${_yyyy}${_MM}${_dd}`;
			break;
		case '3':
			return `${_hh}:${_mm}`;
			break;
		case '4':
			return `${_yyyy}.${_MM}.${_dd}`;
			break;
		case '5':
			return [_yyyy,_MM,_dd,_hh,_mm,_ss];
			break;														  												
	}
};
const request = (params) => {
  return new Promise((resolve, reject) => {
    wx.request({...params,
			enableHttp2:true,
			timeout:'18000',
      success: (result) => { resolve(result) },
      fail: (err) => { 
				wx.showToast({ icon:'none', title: '网络连接错误，稍后再试！' })
				resolve('');
			},
      complete: () => {}
    });
  });
};
const getSystemInfo = () => {
	return new Promise((resolve, reject) => {
		wx.getSystemInfo({
			success: (res)=>{
				const isIOS = res.platform === 'ios';
				if (isIOS) { resolve('ios')}else{ resolve('android')}
			},
      fail: (err) => { resolve('')},			
		})
	})
};
const getNetworkType = () => {
	return new Promise((resolve, reject) => {
		wx.getNetworkType({
			success: (res)=>{
				resolve(res.subtype || res.networkType)
			},
      fail: (err) => { resolve('')},			
		})
	})
};
const getConnectedWifi = () => {
	return new Promise((resolve, reject) => {
		wx.startWifi({
			success:(res) => {
				wx.getConnectedWifi({
					success:(res) => {resolve(res.wifi.SSID)},
					fail: (err) => { resolve('')}
				})
			},
			fail: (err) => {resolve('')},	
		})
	})
};
const scanCode = () => {
	return new Promise((resolve, reject) => {
		wx.scanCode({
			success: (res) => {				
				if (res.path) {
					res.path = decodeURIComponent(res.path)
				}
				resolve(res)	
			},
			fail: (err) => {resolve('')}	
		})		
	})
}

//用于Js截字
const cutStr = (name,num) => {
	var num = num*2;
	var len = 0;
	var scrollFalg = false;
	var newStr = '';
	for (var i = 0; i < name.length; i++) {
		var single = name.charAt(i);
		if (single.match(/[^\x00-\xff]/ig) != null) { len += 2 } else { len += 1;}
		if(len <= num){ newStr += single;}
	};
	if (len > num) { scrollFalg = true }	
	if(scrollFalg){ var nameStr = newStr+'...' }else{ var nameStr = name }
	return nameStr;
};

const formatDateAll = (date, format, isTimeShift) => {
  if (arguments.length < 2 && !date.getTime) {
    format = date;
  }
  typeof format != "string" && (format = "YYYY年MM月DD日 hh时mm分ss秒");
  var week = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "日",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六"
  ];
  var tmp;
  return format.replace(/YYYY|YY|MM|DD|hh|mm|ss|星期|周|www|week/g, function (
    a
  ) {
    switch (a) {
      case "YYYY":
        return date.getFullYear();
      case "YY":
        return (date.getFullYear() + "").slice(2);
      case "MM":
        tmp = date.getMonth() + 1 + "";
        if (isTimeShift) {
          return tmp.length == 1 ? "0" + tmp : tmp;
        }
        return tmp.length == 1 && false ? "0" + tmp : tmp;
      case "DD":
        tmp = date.getDate() + "";
        if (isTimeShift) {
          return tmp.length == 1 ? "0" + tmp : tmp;
        }
        return tmp.length == 1 && false ? "0" + tmp : tmp;
      case "hh":
        tmp = date.getHours() + "";
        return tmp.length == 1 ? "0" + tmp : tmp;
      case "mm":
        tmp = date.getMinutes() + "";
        return tmp.length == 1 ? "0" + tmp : tmp;
      case "ss":
        tmp = date.getSeconds() + "";
        return tmp.length == 1 ? "0" + tmp : tmp;
      case "星期":
        return "星期" + week[date.getDay() + 7];
      case "周":
        return "周" + week[date.getDay() + 7];
      case "week":
        return week[date.getDay()];
      case "www":
        return week[date.getDay()].slice(0, 3);
    }
  });
};
const getQuery = (url,variable)=>{
	if(!url)return(false); 
	var query = url.substring(url.indexOf('?')+1,url.length);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
	var pair = vars[i].split("=");
		if(pair[0] == variable){return pair[1];}
	}
	return(false);
};
const wxLogin = () => {
	return new Promise((resolve, reject) => {
		wx.login({
			 success: (res) => {
					resolve(res) 
			 },
			 fail: (err) => {resolve('')}	
		})
	})
}
const sendLog = (_eventId,_widgetId,_phoneNo,_relUid,_cid,_proInfo) => {
	//埋点
	var _text = {
		event_id: _eventId,
		props:{
			from:'0',
			widget_id:_widgetId,
			phone_no:_phoneNo,
			rel_uid:_relUid
		},	
	};
	if(_cid){ _text.props.cid = _cid }
	if(_proInfo){_text.props = {..._text.props,..._proInfo}};
	_text = encodeURIComponent(JSON.stringify(_text));
	var _time = formatDateAll(new Date(),'YYYY:MM:DD:hh:mm:ss',true);
	var _contenttext = `${_time}/1/400/log/${_text}`;
	var _params = {
		seqid:'0', //请求编号，必填
		curtime:_time,
		deviceid:app.globalData.curDevice.deviceCode, //'phone',
		versionid:'1.0.0',
		platformid:'YST_BJ_PHONE_MINI',
		mac:'0',
		retryseqid:'0', 
		nettype:'',
		wifiid:'',
		innerip:'',
		gatwaymac:'',
		contentcount:'1',
		contenttext:_contenttext
	}
	console.log(_params);
	var _url = config.logApi;
	request({url:_url, data:_params})
}

export {
  formatDate,
	getSystemInfo,
	getNetworkType,
	getConnectedWifi,
	scanCode,
	cutStr,
	request,
	formatDateAll,
	getQuery,
	wxLogin,
	sendLog
}
